package com.mycat.web.content.shiro;

import org.apache.shiro.web.filter.authc.AuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 自定义shiro拦截器，未登录的返回401
 * @author roger.
 * @email luojie@yzworld.cn
 * @date 2016/10/27
 */
public class ShiroAuthFilter extends AuthenticationFilter {

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        if(!getSubject(request,response).isAuthenticated()){
            onLoginFail(response);
            return false;
        }else{
            return true;
        }
    }

    /**
     * 登录失败返回401
     * @param response ServletResponse
     * @throws IOException
     */
    private void onLoginFail(ServletResponse response) throws IOException {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.setContentType("application/json;charset=UTF-8");
        httpResponse.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        httpResponse.getWriter().write("{\"code\":401,\"msg\":\"登录超时，请重新登录！\",\"success\":false}");
    }
}
